package com.winninghlw.windhplocalutils.transmit;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.winninghlw.windhplocalutils.util.HttpRestUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;

/**
 * @author water
 * 2025/3/12 9:28
 */
@RestController
@RequestMapping("/ts")
@Slf4j
public class TransmitController {

    @Autowired
    private HttpRestUtil httpRestUtil;
    @Autowired
    private RestTemplate restTemplate;

    @GetMapping
    public String status() {
        return "200";
    }

    @GetMapping("/hello")
    public String hello(String url) {
        if (!StringUtils.hasText(url)) {
            return "500";
        }
        log.info("hello:{}", url);
        return httpRestUtil.getData(url);
    }

    @GetMapping("/json/cache")
    public String jsonCache(String url) {
        if (!StringUtils.hasText(url)) {
            return "500";
        }
        log.info("jsonCache:{}", url);
        return httpRestUtil.getData(url);
    }

    @PostMapping("/json/update")
    public String jsonCachePost(@RequestBody JsonUpdateDTO ivo) {
        HashMap<Object, Object> map = new HashMap<>();
        try {
            JSONObject data = new JSONObject();
            data.put("file_name", ivo.getFileName());
            data.put("content", ivo.getContent());
            httpRestUtil.postJsonData(ivo.getUrl() + "/json/update", data);
            httpRestUtil.postJsonData(ivo.getUrl()+ "/json/refresh?fileName=" + ivo.getFileName(), null , null);
            map.put("code", 0);
            map.put("msg", "更新成功");
        } catch (Exception e) {
            log.error("更新失败", e);
            map.put("code", 1000);
            map.put("msg", "更新失败:" + e.getMessage());
        }
        return JSON.toJSONString(map);
    }

    /**
     * 查询文件列表
     */
    @GetMapping("/log/list")
    public String jsonList(String url) {
        if (!StringUtils.hasText(url)) {
            return "500";
        }
        log.info("jsonList:{}", url);
        return httpRestUtil.getData(url);
    }

    /**
     * 下载日志文件
     */
    @GetMapping("/log/download")
    public ResponseEntity<Resource> jsonDownload1(String url) {
        if (!StringUtils.hasText(url)) {
            return ResponseEntity.notFound().build();
        }
        if (!url.contains("fileName=")) {
            return ResponseEntity.ok().body(new InputStreamResource(null));
        }
        log.info("jsonDownload:{}", url);
        ResponseEntity<Resource> response = restTemplate.exchange(url, HttpMethod.GET, null, Resource.class);
        HttpHeaders headers = new HttpHeaders();

        // 转发关键响应头
        headers.setContentDisposition(response.getHeaders().getContentDisposition());
        headers.setContentType(response.getHeaders().getContentType());
        headers.setContentLength(response.getHeaders().getContentLength());

        return ResponseEntity.ok()
                .headers(headers)
                .body(response.getBody());
    }
}
